/**
 * Created by 小敏哥 on 2018/1/18.
 */
//获取应用实例
var app = getApp();
var data = {};
var checkRules = {
    name: '^[\u4e00-\u9fa5]+$',
    phone: '^1\\d{10}$',
    detailAddress: '^\\S{5,}$',
};
var checkMsg = {
    name: '请输入正确的收件人姓名！',
    phone: '请输入正确的联系电话！',
    detailAddress: '详细地址长度应不少于5位！',
    area: '请选择所在地区！',
};
var QQMapWX = require('../../utils/qqmap-wx-jssdk.min');
Page({
    data: {
        name: '',
        phone: '',
        area: '',
        detailAddress: '',
        remark: '',
        check: {
            name: false,
            phone: false,
            area: false,
            detailAddress: false,
            remark: true,
        },
        focus: {
            name: false,
            phone: false,
            detailAddress: false,
            area: false,
            remark: false,
        }
    },
    //正则验证用户输入
    checkData(e) {
        let source = e.target.dataset.source;
        let checkData = this.data.check;
        //有验证需求才进行验证
        if (checkRules[source]) {
            let exp = new RegExp(checkRules[source], "g");
            if (exp.test(e.detail.value)) {
                checkData[source] = true;
            }
            else {
                checkData[source] = false;
            }
        }
        else {
            checkData[source] = true;
        }

        this.setData({
            check: checkData
        });

        //缓存输入结果
        this.bindData(e);
    },
    //提交前的全局校验
    checkAll() {
        let checkResult = true;
        let focusData = this.data.focus;
        for (let item in focusData) {
            focusData[item] = false;
        }
        for (let item in this.data.check) {
            if (!this.data.check[item]) {
                focusData[item] = true;
                checkResult = false;
                app.errorToast(checkMsg[item]);
                break;
            }
        }
        this.setData({
            focus: focusData
        });
        return checkResult;

    },
    onLoad(options) {
        //清空微信缓存的数据
        data = {};
        //sessionstorage有值则为编辑
        if (app.getStorageSync('editEMSAddressData')) {
            wx.setNavigationBarTitle({
                title: '编辑地址',
            });
            let initData = app.getStorageSync('editEMSAddressData');
            app.removeStorageSync('editEMSAddressData');
            //编辑时所有校验默认正确
            let checkData = this.data.check;
            for (let item in checkData) {
                checkData[item] = true
            }
            this.setData({
                check: checkData,
                name: initData.name,
                phone: initData.phone,
                area: initData.address.replace(initData.street, ''),
                detailAddress: initData.street,
                remark: initData.remark,
            });
            data.name = initData.name;
            data.phone = initData.phone;
            data.detailAddress = initData.street;
            data.provinceId = initData.provinceId;
            data.provinceName = initData.provinceName;
            data.cityId = initData.cityId;
            data.cityName = initData.cityName;
            data.countyId = initData.countyId;
            data.countyName = initData.countyName;
            data.addressId = initData.addressId;
            data.remark = initData.remark
        }
        else {
            this.initAddressByLocation();
        }
        app.initAddress();
    },

    //根据定位初始化地址
    initAddressByLocation() {
        //寄件人需要初始化地址
        if (app.getStorageSync('addressType') == 'send') {
            let self = this;
            let qqmapsdk = new QQMapWX({
                key: 'KNLBZ-PQW6P-2H4DN-LTE6J-WRC3Q-QFFMG' // 必填
            });
            wx.showToast({
                title: '加载中',
                icon: 'loading',
                duration: 10000
            });
            wx.getLocation({
                type: 'wgs84',
                success: function (res) {
                    //2、根据坐标获取当前位置名称，显示在顶部:腾讯地图逆地址解析
                    qqmapsdk.reverseGeocoder({
                        location: {
                            latitude: res.latitude,
                            longitude: res.longitude
                        },
                        success: function (addressRes) {
                            let address = addressRes.result.ad_info;
                            console.log(address);
                            let provinceId = address.adcode.substr(0, 2) + '0000';
                            let cityId = address.adcode.substr(0, 4) + '00';
                            let countryId = address.adcode;
                            self.setData({
                                area: address.province + address.city + address.district,
                                check: {
                                    name: false,
                                    phone: false,
                                    area: true,
                                    detailAddress: false,
                                },
                            });
                            data.provinceId = provinceId;
                            data.provinceName = address.province;
                            data.cityId = cityId;
                            data.cityName = address.city;
                            data.countyId = countryId;
                            data.countyName = address.district;
                            wx.hideToast();
                        }
                    })
                }
            })
        }
    },
    //将用户输入的信息暂时缓存
    bindData(e) {
        data[e.target.dataset.source] = e.detail.value;
    },

    //取消
    cancel() {
        wx.navigateBack()
    },
    //提交地址
    save() {
        if (!this.checkAll()) {
            return;
        }
        let dataObj = {
            contactName: data.name,
            cellNum: data.phone,
            street: data.detailAddress,
            provinceId: data.provinceId,
            provinceName: data.provinceName,
            cityId: data.cityId,
            cityName: data.cityName,
            countyId: data.countyId,
            countyName: data.countyName,
            fullAddr: data.provinceName + data.cityName + data.countyName + data.detailAddress,
            remark: data.remark ? data.remark : '',
        };
        //区分收件人地址和寄件人地址
        if (app.getStorageSync('addressType') != 'send') {
            dataObj.collectFlag = 1;
        }
        //存在addressId时为编辑
        data.addressId && (dataObj.id = data.addressId);
        let opt = {
            url: app.globalData.host + "/wx/ad/edit.ajax",
            data: dataObj,
            sucFn: (result) => {
                if (result.code == 1000) {
                    wx.navigateBack();
                }
                else {
                    wx.showToast({
                        title: result.msg,
                        icon: 'none',
                        duration: 2000
                    });
                }
            }
        };
        app.ajax(opt);
    },
    // 显示区域选择框
    showAddressPicker() {
        this.setData({
            isShow: true,
        })
    },
    // 隐藏区域选择框
    cancelAddressTap() {
        this.setData({
            isShow: false,
        })
    },

    //选择城市确定按钮
    confirmAddressTap(e) {
        console.log(this.data.value);
        var current_value = this.data.value;
        var provinceName = this.data.proviceData[current_value[0]].name;
        var cityName = this.data.cityData[current_value[1]].name;
        var countyName = "";
        if (this.data.districtData[current_value[2]].name != null) {
            countyName = this.data.districtData[current_value[2]].name;
        }

        let checkData = this.data.check;
        checkData.area = true;
        this.setData({
            check: checkData,
            isShowFootNav: true,
            isAddressShow: false,
            areaStyle: "color:#1a1a1a;font-size:34rpx",
            area: provinceName + cityName + countyName,
            /*   "address.provinceId":this.data.proviceData[current_value[0]].id,
               "address.cityId":this.data.cityData[current_value[1]].id,
               "address.countyId":this.data.districtData[current_value[2]].id,
               "address.provinceName":provinceName,
               "address.cityName":cityName,
               "address.countyName":countyName*/
        });
        data.provinceId = this.data.proviceData[current_value[0]].id;
        data.provinceName = provinceName;
        data.cityId = this.data.cityData[current_value[1]].id;
        data.cityName = cityName;
        data.countyId = this.data.districtData[current_value[2]].id;
        data.countyName = countyName;


    },
    //省市区滑动事件
    bindAddressChange(e) {
        app.bindAddressChange(e);
    }
});